package com.sxz.sbs.module.mine;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.app.App;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.app.GlideApp;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.login.LoginActivity;
import com.sxz.sbs.module.mine.mode.AdminPhoneBean;
import com.sxz.sbs.module.mine.mode.UserInfo;
import com.sxz.sbs.module.mine.presenter.PersonagePresenter;
import com.sxz.sbs.module.mine.view.PersonageView;
import com.sxz.sbs.util.CacheUtil;
import com.sxz.sbs.view.HorizontalCellView;
import com.sxz.sbs.widget.CommonTitle;
import com.sxz.sbs.widget.PhoneDialog;
import com.sxz.sbs.widget.StallAlertDialog;
import com.tian.photopicker.PhotoPicker;

import org.w3c.dom.Text;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author hp
 * @date 2018/1/6
 * 个人中心界面
 */

public class PersonageActivity extends BaseActivity<PersonagePresenter> implements PersonageView {

    @BindView(R.id.view_mine_changepassword)
    HorizontalCellView viewChangePassword;
    @BindView(R.id.personal_name)
    HorizontalCellView personalName;
    @BindView(R.id.personal_phone)
    HorizontalCellView personalPhone;
    @BindView(R.id.personal_company)
    HorizontalCellView personalCompany;
    @BindView(R.id.personal_department)
    HorizontalCellView personalDepartment;
    @BindView(R.id.personal_job)
    HorizontalCellView personalJob;
    @BindView(R.id.personal_entry_date)
    HorizontalCellView personalEntryDate;
    @BindView(R.id.personal_become_date)
    HorizontalCellView personalBecomeDate;
    @BindView(R.id.tiv_personal_head)
    ImageView head;
    @BindView(R.id.technology_phone_one)
    TextView technologyOne;
    @BindView(R.id.technology_phone_two)
    TextView technologyTwo;
    @BindView(R.id.view_mine_generalize_code)
    LinearLayout linMineGeneralizeCode;
    @BindView(R.id.tv_cache)
    public TextView tvCache;
    @BindView(R.id.view_mine_clearCache)
    LinearLayout viewMineClearCache;
    private ProgressDialog progressDialog;
    private int personageId = 0;
    private String unicodeName = "", personagePhone = "";

    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("个人中心").build().show();
        mPresenter.getUserInfo(HttpParamMap.getParamMap());
        mPresenter.getAdminPhone(HttpParamMap.getParamMap());
        try {
            LogUtils.i("CacheUtils.getInstance().getCacheCount()", CacheUtil.getTotalCacheSize(this));
            tvCache.setText(CacheUtil.getTotalCacheSize(this) + "");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personage;
    }

    @Override
    protected PersonagePresenter createPresenter() {
        return new PersonagePresenter();
    }

    @OnClick({R.id.ll_head, R.id.view_mine_gathering, R.id.view_mine_changepassword,
            R.id.tv_login_out, R.id.technology_phone_one, R.id.technology_phone_two, R.id.view_mine_generalize_code, R.id.view_mine_clearCache})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_head:
                PhotoPicker.builder().setSelectPhotoCount(1).
                        start(PersonageActivity.this, 1000);
                break;
            case R.id.view_mine_gathering:
                startActivity(PaymentCodeActivity.class);
                break;
            case R.id.view_mine_changepassword:
                String phone = personalPhone.getRightText();
                if (TextUtils.isEmpty(phone)) {
                    phone = App.preferences.getValue(AppConstant.Preference.USER_NAME);
                }
                Intent intent = new Intent(this, ChangePasswordActivity.class);
                intent.putExtra("user_phone", phone);
                startActivity(intent);
                break;
            case R.id.tv_login_out:
                new StallAlertDialog.Builder(this).setMessage("确定要退出登录吗？").setPositiveButton(new StallAlertDialog.OnPositiveListener() {
                    @Override
                    public void onPositiveClick(View view) {
                        mPresenter.loginOut(HttpParamMap.getParamMap());
                    }
                }).create().show();
                break;
            case R.id.technology_phone_one:
                PhoneDialog.callPhone(PersonageActivity.this,
                        technologyOne.getText().toString());
                break;
            case R.id.technology_phone_two:
                PhoneDialog.callPhone(PersonageActivity.this,
                        technologyTwo.getText().toString());
                break;
            case R.id.view_mine_generalize_code:
                intent = new Intent(PersonageActivity.this, GeneralizeCodeActivity.class);
                intent.putExtra("personageId", personageId + "");
                intent.putExtra("unicodeName", unicodeName);
                intent.putExtra("personagePhone", personagePhone);
                startActivity(intent);
                break;
            case R.id.view_mine_clearCache:
                if (tvCache.getText().toString().equals("0K")) {
                    ToastUtils.showShort("暂无缓存！");
                } else {
                    final ProgressDialog dialog2 = ProgressDialog.show(this, "", "缓存清理中");
                    CacheUtil.clearAllCache(this);
                    new CountDownTimer(1000,1000){

                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
                            dialog2.dismiss();
                            MyHandler handler = new MyHandler(PersonageActivity.this);
                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    }.start();

                }
                break;
            default:
                break;
        }
    }

    static class MyHandler extends Handler {
        WeakReference<Activity> mWeakReference;

        public MyHandler(Activity activity) {
            mWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final Activity activity = mWeakReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    ((TextView)activity.findViewById(R.id.tv_cache)).setText("0K");
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        if (requestCode == 1000) {
            progressDialog = ProgressDialog.show(this, null, "上传中...");
            List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            LogUtils.e(result.get(0) + "-----");
            File file = new File(result.get(0));
            File newFile = new CompressHelper.Builder(this)
                    .setMaxWidth(720)
                    .setMaxHeight(1080)
                    .setQuality(70)
                    .setFileName(System.currentTimeMillis() + "")
                    .setCompressFormat(Bitmap.CompressFormat.JPEG)
                    .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES).getAbsolutePath())
                    .build()
                    .compressToFile(file);
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), newFile);
            MultipartBody.Part filePart = MultipartBody.Part.createFormData("headPic", newFile.getName(), requestFile);
            mPresenter.uploadHead(filePart);
        }


    }

    @Override
    public void onLoginOutSuccess() {
        startActivity(LoginActivity.class);
        App.getInstance().clearActivity();
        App.preferences.setValue(AppConstant.Preference.TOKEN, null);
    }


    @Override
    public void onGetUserInfoSuccess(UserInfo info) {
        if (mIsLive && info != null) {
            personageId = info.getId();
            unicodeName = info.getUnicodeName();
            personagePhone = info.getTxt_Phone();
            GlideApp.with(mContext).load(info.getUrl_HeadPhoto()).placeholder(R.drawable.ic_headportrait)
                    .error(R.drawable.ic_headportrait).circleCrop().into(head);
            personalName.setRightText(info.getTxt_Name());
            personalPhone.setRightText(info.getTxt_Phone());
            personalCompany.setRightText(info.getTxt_CompanyName());
            personalDepartment.setRightText(info.getTxt_DepartmentName());
            personalJob.setRightText(info.getTxt_PositionName());
            personalEntryDate.setRightText(info.getDate_EnterTime().split("\\ ")[0]);
            personalBecomeDate.setRightText(info.getDate_BeFormalTime().split("\\ ")[0]);
        }
    }

    @Override
    public void showError(int errorTag, String msg) {
        super.showError(errorTag, msg);
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onUploadHeadSuccess(String url) {
        if (mIsLive && url != null) {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            GlideApp.with(this).load(url).circleCrop().into(head);
        }
    }

    @Override
    public void onGetAdminPhoneData(List<AdminPhoneBean> data) {
        if (mIsLive) {
            if (data != null) {
                if (data.size() > 0) {
                    technologyOne.setText(data.get(0).getPhone());
                }
                if (data.size() > 1) {
                    technologyTwo.setText(data.get(1).getPhone());
                }

            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
